package com.example.health_life.util;

import com.example.health_life.config.WxConfig;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class WxApiUtil {
    private static final String WX_CODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String WX_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    public Map<String, String> code2Session(String code) {
        String url = String.format("%s?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                WX_CODE2SESSION_URL, wxConfig.getAppid(), wxConfig.getSecret(), code);

        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        try {
            JsonNode jsonNode = objectMapper.readTree(response.getBody());
            Map<String, String> result = new HashMap<>();
            
            if (jsonNode.has("errcode") && jsonNode.get("errcode").asInt() != 0) {
                throw new RuntimeException("微信登录失败：" + jsonNode.get("errmsg").asText());
            }

            result.put("openid", jsonNode.get("openid").asText());
            result.put("session_key", jsonNode.get("session_key").asText());
            if (jsonNode.has("unionid")) {
                result.put("unionid", jsonNode.get("unionid").asText());
            }
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("解析微信登录响应失败", e);
        }
    }

    public Map<String, String> getUserInfo(String accessToken, String openid) {
        String url = String.format("%s?access_token=%s&openid=%s&lang=zh_CN",
                WX_USERINFO_URL, accessToken, openid);

        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        try {
            JsonNode jsonNode = objectMapper.readTree(response.getBody());
            Map<String, String> result = new HashMap<>();
            
            if (jsonNode.has("errcode") && jsonNode.get("errcode").asInt() != 0) {
                throw new RuntimeException("获取用户信息失败：" + jsonNode.get("errmsg").asText());
            }

            result.put("nickname", jsonNode.get("nickname").asText());
            result.put("avatar", jsonNode.get("headimgurl").asText());
            result.put("gender", jsonNode.get("sex").asText());
            
            return result;
        } catch (Exception e) {
            throw new RuntimeException("解析用户信息响应失败", e);
        }
    }
} 